import http from 'http'
import Koa from 'koa'
import WebSocket from 'ws'
import koaStatic from "koa-static";
import koaBody from "koa-body";
import path from "path";
// 路由
import useRouter from './http'

import dotenv from "dotenv";
dotenv.config(); // 需要先执行，后续执行的服务都需要doteenv读取默认配置。
// 中间件
import AuthMiddleware from "./middleware/AuthMiddleware"; // token
import AccessLogMiddleware from "./middleware/AccessLogMiddleware"; // 记录日志

import { serverConfig } from './config'
import MyWebSocket from './websocket/core';
import wsRoutes from './websocket'

const app = new Koa()

app
  .use(koaStatic(path.join(__dirname, "public")))
  .use(koaBody())
  .use(AuthMiddleware)
  .use(AccessLogMiddleware)
  .use(useRouter.routes())


const server = http.createServer(app.callback());
const wss = new WebSocket.Server({ server });

new MyWebSocket(wss,app).addRoutes(wsRoutes)


server.listen(serverConfig.server.port, () => {
  console.log(`-----------listen ${serverConfig.server.port}---------`)
})

// wss.on('connection', (ws, app: http.IncomingMessage) => {
//   // console.log('connection', ws)
//   console.log(app)
// })